package com.qf.test01.utils;

import org.springframework.beans.factory.FactoryBean;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MyProxyFactoryBean implements FactoryBean<Object> {
    private Object target;

    public Object getTarget() {
        return target;
    }

    public void setTarget(Object target) {
        this.target = target;
    }

    @Override
    public Object getObject() throws Exception {
        return Proxy.newProxyInstance(
                this.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                (proxy, method, args) -> {
                    //判断method是不是属于Object类型，如果是，则不做时间统计
                    if (method.getDeclaringClass().equals(Object.class)) {
                        return method.invoke(target, args);
                    }
                    //添加辅助功能
                    long start = System.currentTimeMillis();
                    Object result = method.invoke(target, args);
                    Thread.sleep(100);
                    long end = System.currentTimeMillis();
                    System.out.println("时间：" + (end - start));
                    return result;
                }
        );
    }

    @Override
    public Class<?> getObjectType() {
        return Object.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}
